package com.wittandliz.view.utils
{
	import com.wittandliz.view.UnderConstruction;
	import com.wittandliz.view.events.ViewEvent;
	
	import flash.display.DisplayObject;
	import flash.net.URLRequest;
	
	import mx.controls.Text;
	import mx.core.Application;
	import mx.core.Container;
	import mx.core.IFlexDisplayObject;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	public class Utils
	{
		public static const MAXIMIZE_RATIO : Number = 0.9;
		
		public static function openPopup(windowClass : Class, 
			maximize : Boolean = false) : IFlexDisplayObject
		{
	    	var popup : IFlexDisplayObject = PopUpManager.createPopUp(
	    		Application.application as DisplayObject, 
	    		windowClass, 
	    		true);
	    	if (maximize)
	    	{
	    		popup.width = MAXIMIZE_RATIO * Application.application.width;
	    		popup.height = MAXIMIZE_RATIO * Application.application.height;
	    	}
	    	PopUpManager.centerPopUp(popup);
	    	popup.addEventListener(CloseEvent.CLOSE, onPopupClose);
	    	return popup;
		}
		
		public static function closePopup(popup : IFlexDisplayObject) : void
		{
	    	popup.removeEventListener(CloseEvent.CLOSE, onPopupClose);
			PopUpManager.removePopUp(popup);
		}
		
		public static function onPopupClose(event : CloseEvent) : void
		{
			var popup : IFlexDisplayObject = event.target as IFlexDisplayObject;
			closePopup(popup);
		}

        public static function resizeTextControls(component : UIComponent, width : Number) : void
        {
        	if (component is Text) 
        	{
        		component.width = width - component.x;
        	}            	
        	else if (component is Container)
        	{
        		var children : Array = Container(component).getChildren();
        		for (var i : int; i < children.length; i++)
        		{
        			resizeTextControls(children[i], width);
        		}
        	}
        }
	
	    public static function handleLink(link : String) : void 
	    {
	    	var scheme : String = link.split(":")[0];
			if (scheme == "http") 
			{
				flash.net.navigateToURL(new URLRequest(link), "_blank");
			}
			else if (scheme == "mailto")
			{ 
				flash.net.navigateToURL(new URLRequest(link), "_self");
			}
			else if (scheme == "view")
			{
				var viewName : String = link.split(":")[1];
				if (viewName == "localInfo" || viewName == "photos" || 
					viewName == "wall" || viewName == "faq")
				{
					openPopup(UnderConstruction);
				}
				else 
				{
					var viewEvent : ViewEvent = 
		        		new ViewEvent(ViewEvent.VIEW_CHANGED, viewName);
		        	viewEvent.dispatch();
		  		}
	   		}			
	    }
	}
}